package com.zmj.sy.mom.srv.aps.utils;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.jwt.JWT;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class SySecurityUtils {

    public static String getUserCode() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return "000000";
        }
        HttpServletRequest request = requestAttributes.getRequest();

        // WEB （获取 Authorization 中第一个点到第二个点中的信息，解析后获取用户名）
        String authorization = request.getHeader("Authorization");
        String pc = request.getHeader("Pc");
        if (StringUtils.hasText(pc)&&"new".equals( pc)) {
            return "new";
        }else{
            if (StringUtils.hasText(authorization)) {
                try {
                    String token = authorization.replace("Bearer ", "").trim();
                    JWT jwt = JWT.of(token);
                    return jwt.getPayload("userNum").toString();
                } catch (Exception e) {
                    return "new";
                }
            }
        }


        // PDA （获取 worker 字段中的内容，即用户名）
        String username = ServletUtil.getHeader(request, "worker", "UTF-8");
        if(StringUtils.hasText(username)){
            return username;
        }

        // WEB （获取 Cookie 中的信息，获取 username 字段）
        Cookie cookie = ServletUtil.getCookie(request, "username");
        if(cookie != null){
            username = cookie.getValue();
            return username;
        }

        return "000000";
    }

    public static String getFactoryCode() {
        return "170";
    }

    public static Integer getFactoryId() {
        return 1;
    }
}
